import React, { useState, useEffect } from 'react'
import { Upload, Button, Spin, message } from 'antd'
import { CloudUploadOutlined, PaperClipOutlined } from '@ant-design/icons'
import config from '@/config'

const { uploadURL } = config

const uploadDefaultProps = {
  multiple: true,
  className: 'upload_wrap',
  // accept:
  // 'application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/pdf,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel',
}

const TUpload = ({
  isUpload = true,
  uploadParams,
  uploading = false,
  fileList = [],
  fetchFile,
  fetchDeleteFile,
  setupFileList,
  ...resProps
}: any) => {
  useEffect(() => {
    return () => {
      setupFileList && setupFileList([])
    }
  }, [setupFileList])

  // 文件上传change
  const [_fileList, set_fileList] = useState([])
  const fileChange = (info: any) => {
    let { file, fileList } = info

    if (file.status === 'done') {
      // 上传成功
      message.success(file.response.msg || '上传成功')
      fetchFile && fetchFile(uploadParams, (list: any) => setupFileList(list))
    }

    // 该setState说明 https://github.com/ant-design/ant-design/issues/2423
    set_fileList([...(fileList as [])])
  }

  const deleteFile = ({ id }: any, i: number) => {
    if (fetchDeleteFile && setupFileList) {
      fetchDeleteFile({ fileId: id }, () => {
        const newFileList = fileList.filter(
          (item: any, index: number) => index !== i,
        )
        setupFileList(newFileList)
        fetchFile(uploadParams, (list: any) => setupFileList(list))
      })
    }
  }

  return (
    <div>
      {isUpload && (
        <Upload
          {...uploadDefaultProps}
          action={uploadURL}
          data={uploadParams}
          fileList={_fileList}
          onChange={(info) => fileChange(info)}
          {...resProps}
        >
          <Button>
            <CloudUploadOutlined /> 上传文件
          </Button>
        </Upload>
      )}
      <Spin spinning={uploading}>
        <div className="uploadFileList">
          {fileList.map((_: any, i: number) => (
            <div key={i} className="file_item">
              <PaperClipOutlined />
              <span className="file_name" title={_['name']}>
                {_['name']}
              </span>
              <a href={_['url']}>下载</a>
              <a href={_['viewUrl']} target="_blank" rel="noopener noreferrer">
                预览
              </a>
              {isUpload && (
                <span className="pointer" onClick={() => deleteFile(_, i)}>
                  删除
                </span>
              )}
            </div>
          ))}
        </div>
      </Spin>
    </div>
  )
}

export default TUpload
